package com.feng.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feng.chat.common.Common;
import com.feng.chat.dto.*;
import com.feng.chat.entity.*;
import com.feng.chat.mapper.*;
import com.feng.chat.service.IContactService;
import com.feng.chat.service.IGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.chat.service.ITalkSessionService;
import com.feng.chat.utils.GetUserUtil;
import com.feng.chat.utils.MessageUtil;
import com.feng.chat.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 聊天群组表 服务实现类
 * </p>
 *
 * @author dyf
 * @since 2022-05-31
 */
@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupChat> implements IGroupService {
    @Autowired
    private IContactService contactService;

    @Autowired
    private ITalkSessionService talkSessionService;

    @Autowired
    private GroupMemberMapper groupMemberMapper;

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private GroupNoticeMapper groupNoticeMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private TalkRecordsMapper talkRecordsMapper;

    @Autowired
    private TalkRecordsInviteMapper talkRecordsInviteMapper;

    /**
     * 获取邀请好友的好友列表
     *
     * @param uid
     * @param group_id
     * @return
     */
    @Override
    public Result invites(Integer uid, Integer group_id) {

        Result result = contactService.friendList(uid);

        List<ContactListDTO> data = (List<ContactListDTO>) result.getData();
        QueryWrapper<GroupMember> groupMemberQueryWrapper = new QueryWrapper<>();
        groupMemberQueryWrapper.eq("group_id", group_id).eq("is_quit", 0);
        List<GroupMember> groupMembers = groupMemberMapper.selectList(groupMemberQueryWrapper);

        List<ContactListDTO> contactListDTOS = new ArrayList<>();
        contactListDTOS = data.stream().map(item -> {
            for (GroupMember groupMember : groupMembers) {
                if (item.getId() == groupMember.getUserId()) {
                    return item;
                }
            }
            return null;
        }).collect(Collectors.toList());
        data.removeAll(contactListDTOS);

        return Result.success(data);
    }

    /**
     * 创建群聊
     *
     * @param uid
     * @param ids
     * @param group_name
     * @return
     */
    @Transactional
    @Override
    public Result create(Integer uid, List<Integer> ids, String group_name) {
        GroupChat group = new GroupChat();
        group.setCreatorId(uid);
        group.setGroupName(group_name);
        group.setMaxNum(100);
        groupMapper.insert(group);

        GroupMember groupMember1 = new GroupMember();
        groupMember1.setGroupId(group.getId());
        groupMember1.setUserId(uid);
        groupMember1.setLeader(2);
        Users users1 = usersMapper.selectById(uid);
        groupMember1.setUserCard(users1.getNickName());
        groupMemberMapper.insert(groupMember1);

        TalkRecords talkRecords = new TalkRecords();
        talkRecords.setTalkType(2);
        talkRecords.setMsgType(9);
        talkRecords.setGroupRead(uid.toString());
        talkRecords.setUserId(0);
        talkRecords.setReceiverId(group.getId());
        talkRecordsMapper.insert(talkRecords);

        TalkRecordsInvite talkRecordsInvite = new TalkRecordsInvite();
        talkRecordsInvite.setRecordId(talkRecords.getId());
        talkRecordsInvite.setType(1);
        talkRecordsInvite.setOperateUserId(uid);
        List<String> collect = ids.stream().map(String::valueOf).collect(Collectors.toList());
        String join = String.join(",", collect);
        talkRecordsInvite.setUserIds(join);
        talkRecordsInviteMapper.insert(talkRecordsInvite);


        //新建会话
        TalkCreateVO talkCreateVO = new TalkCreateVO();
        talkCreateVO.setTalk_type(2);
        talkCreateVO.setReceiver_id(group.getId());

        talkSessionService.create(uid, talkCreateVO);

        for (Integer id : ids) {
            GroupMember groupMember = new GroupMember();
            groupMember.setGroupId(group.getId());
            groupMember.setUserId(id);
            Users users = usersMapper.selectById(id);
            groupMember.setUserCard(users.getNickName());
            groupMemberMapper.insert(groupMember);

            talkSessionService.create(id, talkCreateVO);
        }
        Map<String, Integer> map = new HashMap<>();
        map.put("group_id", group.getId());
        return Result.success(map);
    }

    /**
     * 获取已加入的群聊列表
     *
     * @param uid
     * @return
     */
    @Override
    public Result list(Integer uid) {
        QueryWrapper<GroupMember> groupMemberQueryWrapper = new QueryWrapper<>();
        groupMemberQueryWrapper.eq("user_id", uid).eq("is_quit", 0).orderByDesc("updated_at");
        List<GroupMember> groupMembers = groupMemberMapper.selectList(groupMemberQueryWrapper);
        List<GroupListDTO> groupListDTOS = new ArrayList<>();
        groupListDTOS = groupMembers.stream().map(item -> {
            GroupChat groupChat = groupMapper.selectById(item.getGroupId());

            GroupListDTO groupListDTO = new GroupListDTO();
            groupListDTO.setAvatar(groupChat.getAvatar());
            groupListDTO.setGroup_name(groupChat.getGroupName());
            groupListDTO.setId(groupChat.getId());
            QueryWrapper<TalkSession> talkSessionQueryWrapper = new QueryWrapper<>();
            talkSessionQueryWrapper.eq("talk_type", 2).eq("user_id", uid).eq("receiver_id", groupChat.getId());
            TalkSession talkSession = talkSessionService.getOne(talkSessionQueryWrapper);
            groupListDTO.setIs_disturb(talkSession.getIsDisturb());
            groupListDTO.setLeader(item.getLeader());
            groupListDTO.setProfile(groupChat.getProfile());

            return groupListDTO;
        }).collect(Collectors.toList());

        Map<String, List<GroupListDTO>> map = new HashMap<>();
        map.put("rows", groupListDTOS);
        return Result.success(map);
    }

    /**
     * 获取群聊信息
     *
     * @param uid
     * @param group_id
     * @return
     */
    @Override
    public Result detail(Integer uid, Integer group_id) {
        GroupDetailDTO groupDetailDTO = new GroupDetailDTO();

        GroupChat groupChat = groupMapper.selectById(group_id);
        groupDetailDTO.setAvatar(groupChat.getAvatar());
        groupDetailDTO.setCreated_at(groupChat.getCreatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
        groupDetailDTO.setGroup_id(groupChat.getId());
        groupDetailDTO.setGroup_name(groupChat.getGroupName());
        groupDetailDTO.setProfile(groupChat.getProfile());
        groupDetailDTO.setNo_message(groupChat.getIsMute());

        QueryWrapper<GroupMember> groupMemberQueryWrapper = new QueryWrapper<>();
        groupMemberQueryWrapper.eq("group_id", group_id).eq("user_id", uid).eq("is_quit", 0);
        GroupMember groupMember = groupMemberMapper.selectOne(groupMemberQueryWrapper);
        groupDetailDTO.setVisit_card(groupMember.getUserCard());
        if (groupMember.getLeader() == 0) {
            groupDetailDTO.setIs_manager(false);
        } else {
            groupDetailDTO.setIs_manager(true);
        }
        Users user = usersMapper.selectById(uid);
        groupDetailDTO.setManager_nickname(user.getNickName());

        QueryWrapper<TalkSession> talkSessionQueryWrapper = new QueryWrapper<>();
        talkSessionQueryWrapper.eq("talk_type", 2).eq("user_id", uid).eq("receiver_id", group_id).eq("is_delete", 0);
        TalkSession talkSession = talkSessionService.getOne(talkSessionQueryWrapper);
        groupDetailDTO.setIs_disturb(talkSession.getIsDisturb());

        GroupNotice item = null;
        QueryWrapper<GroupNotice> groupNoticeQueryWrapper = new QueryWrapper<>();
        groupNoticeQueryWrapper.eq("group_id", group_id).orderByDesc("updated_at").eq("is_delete", 0).last("limit 1");
        GroupNotice groupNotice = groupNoticeMapper.selectOne(groupNoticeQueryWrapper);

        groupNoticeQueryWrapper.eq("is_top", 1);
        GroupNotice top = groupNoticeMapper.selectOne(groupNoticeQueryWrapper);

        if (top != null) {
            item = top;
        } else {
            item = groupNotice;
        }
        NoticeVO noticeVO = new NoticeVO();
        noticeVO.setConfirm_users(item.getConfirmUsers());
        noticeVO.setContent(item.getContent());
        noticeVO.setCreated_at(item.getCreatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
        noticeVO.setCreator_id(item.getCreatorId());
        noticeVO.setGroup_id(item.getGroupId());
        noticeVO.setId(item.getId());
        noticeVO.setIs_confirm(item.getIsConfirm());
        noticeVO.setIs_delete(item.getIsDelete());
        noticeVO.setIs_top(item.getIsTop());
        noticeVO.setTitle(item.getTitle());
        noticeVO.setUpdated_at(item.getUpdatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));

        groupDetailDTO.setNotice(noticeVO);

        return Result.success(groupDetailDTO);
    }

    /**
     * 获取群聊成员
     *
     * @param group_id
     * @return
     */
    @Override
    public Result memberList(Integer group_id) {
        QueryWrapper<GroupMember> groupMemberQueryWrapper = new QueryWrapper<>();
        groupMemberQueryWrapper.eq("group_id", group_id).eq("is_quit", 0).orderByDesc("leader");
        List<GroupMember> groupMembers = groupMemberMapper.selectList(groupMemberQueryWrapper);
        List<GroupMemberDTO> groupMemberDTOS = new ArrayList<>();
        groupMemberDTOS = groupMembers.stream().map(item -> {
            GroupMemberDTO groupMemberDTO = new GroupMemberDTO();
            groupMemberDTO.setId(item.getId());
            groupMemberDTO.setIs_mute(item.getIsMute());
            groupMemberDTO.setLeader(item.getLeader());
            groupMemberDTO.setUser_card(item.getUserCard());
            groupMemberDTO.setUser_id(item.getUserId());

            Users user = usersMapper.selectById(item.getUserId());
            groupMemberDTO.setAvatar(user.getAvatar());
            groupMemberDTO.setGender(user.getGender());
            groupMemberDTO.setMotto(user.getMotto());
            groupMemberDTO.setNickname(user.getNickName());
            return groupMemberDTO;
        }).collect(Collectors.toList());
        return Result.success(groupMemberDTOS);
    }

    /**
     * 根据群id获取群公告信息
     *
     * @param group_id
     * @return
     */
    @Override
    public Result noticeList(Integer group_id) {
        QueryWrapper<GroupNotice> groupNoticeQueryWrapper = new QueryWrapper<>();
        groupNoticeQueryWrapper.eq("group_id", group_id).orderByDesc("updated_at").eq("is_delete", 0);
        List<GroupNotice> groupNotices = groupNoticeMapper.selectList(groupNoticeQueryWrapper);

        List<NoticeVO> noticeVOS = new ArrayList<>();

        noticeVOS = groupNotices.stream().map(item -> {
            NoticeVO noticeVO = new NoticeVO();
            noticeVO.setConfirm_users(item.getConfirmUsers());
            noticeVO.setContent(item.getContent());
            noticeVO.setCreated_at(item.getCreatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
            noticeVO.setCreator_id(item.getCreatorId());
            noticeVO.setGroup_id(item.getGroupId());
            noticeVO.setId(item.getId());
            noticeVO.setIs_confirm(item.getIsConfirm());
            noticeVO.setIs_delete(item.getIsDelete());
            noticeVO.setIs_top(item.getIsTop());
            noticeVO.setTitle(item.getTitle());
            noticeVO.setUpdated_at(item.getUpdatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));

            Users user = usersMapper.selectById(item.getCreatorId());
            noticeVO.setAvatar(user.getAvatar());
            noticeVO.setNickname(user.getNickName());

            return noticeVO;
        }).collect(Collectors.toList());

        Map<String, List<NoticeVO>> map = new HashMap<>();
        map.put("rows", noticeVOS);
        return Result.success(map);
    }

    /**
     * 设置用户群名片
     *
     * @param uid
     * @param group_id
     * @param visit_card
     * @return
     */
    @Override
    public Result memberRemark(Integer uid, Integer group_id, String visit_card) {
        QueryWrapper<GroupMember> groupMemberQueryWrapper = new QueryWrapper<>();
        groupMemberQueryWrapper.eq("group_id", group_id).eq("user_id", uid).eq("is_quit", 0);
        GroupMember groupMember = groupMemberMapper.selectOne(groupMemberQueryWrapper);
        if (groupMember != null && !groupMember.getUserCard().equals(visit_card)) {
            groupMember.setUserCard(visit_card);
            groupMemberMapper.updateById(groupMember);
            return Result.success();
        }
        return Result.fail();
    }

    /**
     * 邀请好友进群
     * @param uid
     * @param group_id
     * @param ids
     * @return
     */
    @Override
    public Result invite(Integer uid, Integer group_id, String ids) {

        String[] user_ids = ids.split(",");
        for (String user_id : user_ids) {

            QueryWrapper<GroupMember> groupMemberQueryWrapper = new QueryWrapper<>();
            groupMemberQueryWrapper.eq("group_id",group_id).eq("user_id",Integer.parseInt(user_id));
            GroupMember groupMember = groupMemberMapper.selectOne(groupMemberQueryWrapper);
            if (groupMember!=null){
                Users users = usersMapper.selectById(Integer.parseInt(user_id));
                groupMember.setUserCard(users.getNickName());
                groupMember.setLeader(0);
                groupMember.setIsMute(0);
                groupMember.setIsQuit(0);
                groupMember.setDeletedAt(null);
                groupMemberMapper.updateById(groupMember);
            }else {
                groupMember = new GroupMember();
                groupMember.setGroupId(group_id);
                groupMember.setUserId(Integer.parseInt(user_id));
                Users users = usersMapper.selectById(Integer.parseInt(user_id));
                groupMember.setUserCard(users.getNickName());
                groupMemberMapper.insert(groupMember);
            }


            TalkCreateVO talkCreateVO = new TalkCreateVO();
            talkCreateVO.setReceiver_id(group_id);
            talkCreateVO.setTalk_type(2);
            talkSessionService.create(Integer.parseInt(user_id),talkCreateVO);
        }

        TalkRecords talkRecords = new TalkRecords();
        talkRecords.setTalkType(2);
        talkRecords.setMsgType(9);
        talkRecords.setGroupRead(uid.toString());
        talkRecords.setReceiverId(group_id);
        talkRecords.setUserId(0);
        talkRecordsMapper.insert(talkRecords);

        TalkRecordsInvite talkRecordsInvite = new TalkRecordsInvite();
        talkRecordsInvite.setRecordId(talkRecords.getId());
        talkRecordsInvite.setType(1);
        talkRecordsInvite.setOperateUserId(uid);
        talkRecordsInvite.setUserIds(ids);
        talkRecordsInviteMapper.insert(talkRecordsInvite);

        KeepAlive keepAlive = new KeepAlive();
        keepAlive.setEvent(Common.EVENT_TALK);

        EventTalkVO eventTalkVO = new EventTalkVO();
        eventTalkVO.setReceiver_id(group_id);
        eventTalkVO.setSender_id(talkRecords.getUserId());
        eventTalkVO.setTalk_type(2);

        EventTalkDataVO eventTalkDataVO = new EventTalkDataVO();
        eventTalkDataVO.setId(talkRecords.getId());
        eventTalkDataVO.setCreated_at(talkRecords.getCreatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
        eventTalkDataVO.setIs_mark(talkRecords.getIsMark());
        eventTalkDataVO.setIs_read(talkRecords.getIsRead());
        eventTalkDataVO.setIs_revoke(talkRecords.getIsRevoke());
        eventTalkDataVO.setMsg_type(talkRecords.getMsgType());
        eventTalkDataVO.setReceiver_id(talkRecords.getReceiverId());
        eventTalkDataVO.setTalk_type(talkRecords.getTalkType());
        eventTalkDataVO.setUser_id(talkRecords.getUserId());
        eventTalkDataVO.setContent(MessageUtil.getMessageType(9,talkRecords.getContent()));

        InviteVO inviteVO = new InviteVO();
        inviteVO.setType(talkRecordsInvite.getType());
        Users operate_user = usersMapper.selectById(talkRecordsInvite.getOperateUserId());
        UserVO userVO = new UserVO();
        userVO.setNickname(operate_user.getNickName());
        userVO.setId(operate_user.getId());
        inviteVO.setOperate_user(userVO);
        List<UserVO> userVOS = new ArrayList<>();
        for (String user_id : user_ids) {
            Users users = usersMapper.selectById(Integer.parseInt(user_id));
            UserVO userVO1 = new UserVO();
            userVO1.setId(users.getId());
            userVO1.setNickname(users.getNickName());
            userVOS.add(userVO1);
        }
        inviteVO.setUsers(userVOS);

        eventTalkDataVO.setInvite(inviteVO);
        eventTalkVO.setData(eventTalkDataVO);
        keepAlive.setContent(eventTalkVO);

        GetUserUtil.sendMessage(keepAlive, uid);

        List<Integer> groupMember = groupMemberMapper.getGroupMember(group_id);
        groupMember.remove(uid);
        for (Integer user_id : groupMember) {
            if (GetUserUtil.isOnLine(user_id) == 1) {
                GetUserUtil.sendMessage(keepAlive, user_id);
            }
        }

        return Result.success();
    }

    /**
     * 退出群聊
     * @param uid
     * @param group_id
     * @return
     */
    @Override
    public Result secede(Integer uid, Integer group_id) {
        QueryWrapper<GroupMember> groupMemberQueryWrapper = new QueryWrapper<>();
        groupMemberQueryWrapper.eq("group_id",group_id).eq("user_id",uid);
        GroupMember groupMember = groupMemberMapper.selectOne(groupMemberQueryWrapper);
        if (groupMember!=null){
            groupMember.setIsQuit(1);
            groupMember.setDeletedAt(LocalDateTime.now());
            groupMemberMapper.updateById(groupMember);
        }

        TalkRecords talkRecords = new TalkRecords();
        talkRecords.setTalkType(2);
        talkRecords.setMsgType(9);
        talkRecords.setGroupRead(uid.toString());
        talkRecords.setUserId(0);
        talkRecords.setReceiverId(group_id);
        talkRecordsMapper.insert(talkRecords);

        TalkRecordsInvite talkRecordsInvite = new TalkRecordsInvite();
        talkRecordsInvite.setRecordId(talkRecords.getId());
        talkRecordsInvite.setType(2);
        talkRecordsInvite.setOperateUserId(uid);
        talkRecordsInvite.setUserIds(uid.toString());
        talkRecordsInviteMapper.insert(talkRecordsInvite);


        KeepAlive keepAlive = new KeepAlive();
        keepAlive.setEvent(Common.EVENT_TALK);

        EventTalkVO eventTalkVO = new EventTalkVO();
        eventTalkVO.setReceiver_id(group_id);
        eventTalkVO.setSender_id(talkRecords.getUserId());
        eventTalkVO.setTalk_type(2);

        EventTalkDataVO eventTalkDataVO = new EventTalkDataVO();
        eventTalkDataVO.setId(talkRecords.getId());
        eventTalkDataVO.setCreated_at(talkRecords.getCreatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
        eventTalkDataVO.setIs_mark(talkRecords.getIsMark());
        eventTalkDataVO.setIs_read(talkRecords.getIsRead());
        eventTalkDataVO.setIs_revoke(talkRecords.getIsRevoke());
        eventTalkDataVO.setMsg_type(talkRecords.getMsgType());
        eventTalkDataVO.setReceiver_id(talkRecords.getReceiverId());
        eventTalkDataVO.setTalk_type(talkRecords.getTalkType());
        eventTalkDataVO.setUser_id(talkRecords.getUserId());
        eventTalkDataVO.setContent(MessageUtil.getMessageType(9,talkRecords.getContent()));

        InviteVO inviteVO = new InviteVO();
        inviteVO.setType(talkRecordsInvite.getType());
        Users operate_user = usersMapper.selectById(talkRecordsInvite.getOperateUserId());
        UserVO userVO = new UserVO();
        userVO.setNickname(operate_user.getNickName());
        userVO.setId(operate_user.getId());
        inviteVO.setOperate_user(userVO);
        List<UserVO> userVOS = new ArrayList<>();
        String[] user_ids = talkRecordsInvite.getUserIds().split(",");

        for (String user_id : user_ids) {
            Users users = usersMapper.selectById(Integer.parseInt(user_id));
            UserVO userVO1 = new UserVO();
            userVO1.setId(users.getId());
            userVO1.setNickname(users.getNickName());
            userVOS.add(userVO1);
        }
        inviteVO.setUsers(userVOS);

        eventTalkDataVO.setInvite(inviteVO);
        eventTalkVO.setData(eventTalkDataVO);
        keepAlive.setContent(eventTalkVO);

        GetUserUtil.sendMessage(keepAlive, uid);

        List<Integer> groupMembers = groupMemberMapper.getGroupMember(group_id);
        groupMembers.remove(uid);
        for (Integer user_id : groupMembers) {
            if (GetUserUtil.isOnLine(user_id) == 1) {
                GetUserUtil.sendMessage(keepAlive, user_id);
            }
        }

        return Result.success();
    }

    /**
     * 添加群公告
     * @param uid
     * @param noticeEditVO
     * @return
     */
    @Override
    public Result noticeEdit(Integer uid, NoticeEditVO noticeEditVO) {
        if (noticeEditVO.getNotice_id()==0){//添加群公告
            GroupNotice groupNotice = new GroupNotice();
            groupNotice.setGroupId(noticeEditVO.getGroup_id());
            groupNotice.setCreatorId(uid);
            groupNotice.setTitle(noticeEditVO.getTitle());
            groupNotice.setContent(noticeEditVO.getContent());
            groupNotice.setIsTop(noticeEditVO.getIs_top());
            groupNotice.setIsConfirm(noticeEditVO.getIs_confirm());
            groupNoticeMapper.insert(groupNotice);

            return Result.success();
        }else {//修改群公告
            GroupNotice groupNotice = groupNoticeMapper.selectById(noticeEditVO.getNotice_id());
            groupNotice.setTitle(noticeEditVO.getTitle());
            groupNotice.setContent(noticeEditVO.getContent());
            groupNotice.setIsConfirm(noticeEditVO.getIs_confirm());
            groupNotice.setIsTop(noticeEditVO.getIs_top());
            groupNoticeMapper.updateById(groupNotice);

            return Result.success();
        }
    }

    /**
     * 修改群信息
     * @param group_id
     * @param avatar
     * @param group_name
     * @param profile
     * @return
     */
    @Override
    public Result setting(Integer group_id, String avatar, String group_name, String profile) {
        GroupChat groupChat = groupMapper.selectById(group_id);
        groupChat.setAvatar(avatar);
        groupChat.setGroupName(group_name);
        groupChat.setProfile(profile);
        groupMapper.updateById(groupChat);
        return Result.success();
    }

    /**
     * 移除群成员
     * @param uid
     * @param group_id
     * @param members_ids
     * @return
     */
    @Override
    public Result memberRemove(Integer uid, Integer group_id, String members_ids) {
        String[] ids = members_ids.split(",");
        for (String id : ids) {
            QueryWrapper<GroupMember> groupMemberQueryWrapper = new QueryWrapper<>();
            groupMemberQueryWrapper.eq("group_id",group_id).eq("user_id",Integer.parseInt(id));
            GroupMember groupMember = groupMemberMapper.selectOne(groupMemberQueryWrapper);
            groupMember.setIsQuit(1);
            groupMember.setDeletedAt(LocalDateTime.now());
            groupMemberMapper.updateById(groupMember);
        }

        TalkRecords talkRecords = new TalkRecords();
        talkRecords.setTalkType(2);
        talkRecords.setMsgType(9);
        talkRecords.setGroupRead(uid.toString());
        talkRecords.setUserId(0);
        talkRecords.setReceiverId(group_id);
        talkRecordsMapper.insert(talkRecords);

        TalkRecordsInvite talkRecordsInvite = new TalkRecordsInvite();
        talkRecordsInvite.setRecordId(talkRecords.getId());
        talkRecordsInvite.setType(3);
        talkRecordsInvite.setOperateUserId(uid);
        talkRecordsInvite.setUserIds(members_ids);
        talkRecordsInviteMapper.insert(talkRecordsInvite);

        KeepAlive keepAlive = new KeepAlive();
        keepAlive.setEvent(Common.EVENT_TALK);

        EventTalkVO eventTalkVO = new EventTalkVO();
        eventTalkVO.setReceiver_id(group_id);
        eventTalkVO.setSender_id(talkRecords.getUserId());
        eventTalkVO.setTalk_type(2);

        EventTalkDataVO eventTalkDataVO = new EventTalkDataVO();
        eventTalkDataVO.setId(talkRecords.getId());
        eventTalkDataVO.setCreated_at(talkRecords.getCreatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
        eventTalkDataVO.setIs_mark(talkRecords.getIsMark());
        eventTalkDataVO.setIs_read(talkRecords.getIsRead());
        eventTalkDataVO.setIs_revoke(talkRecords.getIsRevoke());
        eventTalkDataVO.setMsg_type(talkRecords.getMsgType());
        eventTalkDataVO.setReceiver_id(talkRecords.getReceiverId());
        eventTalkDataVO.setTalk_type(talkRecords.getTalkType());
        eventTalkDataVO.setUser_id(talkRecords.getUserId());
        eventTalkDataVO.setContent(MessageUtil.getMessageType(9,talkRecords.getContent()));


        InviteVO inviteVO = new InviteVO();
        inviteVO.setType(talkRecordsInvite.getType());
        Users operate_user = usersMapper.selectById(talkRecordsInvite.getOperateUserId());
        UserVO userVO = new UserVO();
        userVO.setNickname(operate_user.getNickName());
        userVO.setId(operate_user.getId());
        inviteVO.setOperate_user(userVO);
        List<UserVO> userVOS = new ArrayList<>();
        String[] user_ids = talkRecordsInvite.getUserIds().split(",");

        for (String user_id : user_ids) {
            Users users = usersMapper.selectById(Integer.parseInt(user_id));
            UserVO userVO1 = new UserVO();
            userVO1.setId(users.getId());
            userVO1.setNickname(users.getNickName());
            userVOS.add(userVO1);
        }
        inviteVO.setUsers(userVOS);

        eventTalkDataVO.setInvite(inviteVO);
        eventTalkVO.setData(eventTalkDataVO);
        keepAlive.setContent(eventTalkVO);

        GetUserUtil.sendMessage(keepAlive, uid);

        List<Integer> groupMembers = groupMemberMapper.getGroupMember(group_id);
        groupMembers.remove(uid);
        for (Integer user_id : groupMembers) {
            if (GetUserUtil.isOnLine(user_id) == 1) {
                GetUserUtil.sendMessage(keepAlive, user_id);
            }
        }

        return Result.success();
    }

    /**
     * 解散群聊
     * @param uid
     * @param group_id
     * @return
     */
    @Override
    public Result dismiss(Integer uid, Integer group_id) {
        GroupChat groupChat = groupMapper.selectById(group_id);
        groupChat.setIsDismiss(1);
        groupChat.setDismissedAt(LocalDateTime.now());
        groupMapper.updateById(groupChat);

        TalkRecords talkRecords = new TalkRecords();
        talkRecords.setTalkType(2);
        talkRecords.setMsgType(0);
        talkRecords.setGroupRead(uid.toString());
        talkRecords.setUserId(uid);
        talkRecords.setReceiverId(group_id);
        talkRecords.setContent("群组已被群主或管理员解散！");
        talkRecordsMapper.insert(talkRecords);

        KeepAlive keepAlive = new KeepAlive();
        keepAlive.setEvent(Common.EVENT_TALK);

        EventTalkVO eventTalkVO = new EventTalkVO();
        eventTalkVO.setTalk_type(2);
        eventTalkVO.setSender_id(talkRecords.getUserId());
        eventTalkVO.setReceiver_id(talkRecords.getReceiverId());

        EventTalkDataVO eventTalkDataVO = new EventTalkDataVO();
        Users users = usersMapper.selectById(talkRecords.getUserId());
        eventTalkDataVO.setAvatar(users.getAvatar());
        eventTalkDataVO.setContent(talkRecords.getContent());
        eventTalkDataVO.setCreated_at(talkRecords.getCreatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
        eventTalkDataVO.setId(talkRecords.getId());
        eventTalkDataVO.setIs_mark(talkRecords.getIsMark());
        eventTalkDataVO.setIs_read(talkRecords.getIsRead());
        eventTalkDataVO.setIs_revoke(talkRecords.getIsRevoke());
        eventTalkDataVO.setMsg_type(talkRecords.getMsgType());
        eventTalkDataVO.setNickname(users.getNickName());
        eventTalkDataVO.setReceiver_id(talkRecords.getReceiverId());
        eventTalkDataVO.setTalk_type(talkRecords.getTalkType());
        eventTalkDataVO.setUser_id(talkRecords.getUserId());

        eventTalkVO.setData(eventTalkDataVO);
        keepAlive.setContent(eventTalkVO);

        GetUserUtil.sendMessage(keepAlive, uid);

        List<Integer> groupMembers = groupMemberMapper.getGroupMember(group_id);
        groupMembers.remove(uid);
        for (Integer user_id : groupMembers) {
            if (GetUserUtil.isOnLine(user_id) == 1) {
                GetUserUtil.sendMessage(keepAlive, user_id);
            }
        }

        return Result.success();
    }

}
